package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.system.dtos.dto.AgentTreeDTO;
import com.rightsidetech.system.dtos.dto.StoreTreeDTO;
import com.rightsidetech.system.dtos.request.*;
import com.rightsidetech.system.dtos.response.CompanyAreaResp;
import com.rightsidetech.system.dtos.response.CompanyManageAreaResp;
import com.rightsidetech.system.dtos.response.RegionTreeResp;
import com.rightsidetech.system.entity.SysCompanyArea;
import com.rightsidetech.system.entity.SysUserLoginHistory;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysCompanyAreaService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-10-22 11:34
 */
@Service("sysCompanyAreaServiceImpl")
public class SysCompanyAreaServiceImpl implements SysCompanyAreaService {
    @Resource
    private SysCompanyAreaMapper sysCompanyAreaMapper;
    @Resource
    private SysUserLoginInfoMapper sysUserLoginInfoMapper;
    @Resource
    private SysUserLoginHistoryMapper sysUserLoginHistoryMapper;
    @Resource
    private SysAgentInfoMapper sysAgentInfoMapper;
    @Resource
    private SysStoreInfoMapper sysStoreInfoMapper;

    @Override
    public ResponseData<PageInfo<CompanyAreaResp>> page(CompanyAreaReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CompanyAreaResp> list = sysCompanyAreaMapper.page(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData<List<CompanyManageAreaResp>> selectList(Long areaId) {
        return ResponseData.success(sysCompanyAreaMapper.selectList(null,areaId));
    }

    @Override
    public ResponseData saveCompanyArea(CompanyAreaAddReq req, Long loginInfoId) {
        SysCompanyArea sysCompanyArea = sysCompanyAreaMapper.countAreaByName(req.getName());
        if (!ObjectUtils.isEmpty(sysCompanyArea)){
            return ResponseData.fail("该大区名称已存在");
        }
        SysCompanyArea area = new SysCompanyArea();
        area.setName(req.getName());
        area.setCreaterId(loginInfoId);
        area.setCreatedAt(new Date());
        area.setMobileNo(req.getMobileNo());
        area.setPrincipalName(req.getPrincipalName());
        sysCompanyAreaMapper.insertSelective(area);
        return ResponseData.success();
    }

    @Override
    public ResponseData updateCompanyArea(CompanyAreaUpdateReq req, Long loginInfoId) {
        SysCompanyArea companyArea = sysCompanyAreaMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(companyArea)){
            return ResponseData.fail(CodeIdEnum.NOAREA);
        }
        if (companyArea.getIsDeleted() == 1){
            return ResponseData.fail(CodeIdEnum.NOAREA);
        }
        SysCompanyArea sysCompanyArea = sysCompanyAreaMapper.countAreaByName(req.getName());
        if (!ObjectUtils.isEmpty(sysCompanyArea) && !sysCompanyArea.getId().equals(req.getId())){
            return ResponseData.fail("该大区名称已存在");
        }

        SysCompanyArea area = new SysCompanyArea();
        area.setId(req.getId());
        area.setName(req.getName());
        area.setMobileNo(req.getMobileNo());
        area.setPrincipalName(req.getPrincipalName());
        area.setUpdaterId(loginInfoId);
        area.setUpdatedAt(new Date());
        sysCompanyAreaMapper.updateByPrimaryKeySelective(area);
        return ResponseData.success();
    }

    @Override
    public ResponseData updateStatus(UpdateStatusReq req, Long loginInfoId) {
        if (req.getStatus() == 0){
            return ResponseData.fail("无法改为已创建");
        }
        SysCompanyArea area = sysCompanyAreaMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(area)){
            return ResponseData.fail("未找到此大区");
        }
        if (req.getStatus().equals(area.getStatus())){
            return ResponseData.fail("不可修改同一状态");
        }

        SysCompanyArea companyArea = new SysCompanyArea();
        companyArea.setId(area.getId());
        companyArea.setStatus(req.getStatus());
        companyArea.setUpdaterId(loginInfoId);
        companyArea.setUpdatedAt(new Date());
        sysCompanyAreaMapper.updateStatus(companyArea);

        //关闭 有账号 退出登录
        if (req.getStatus() == 1){
            List<SysUserLoginInfo> loginInfoList = sysUserLoginInfoMapper.findByAreaId(area.getId());
            for (SysUserLoginInfo loginInfo : loginInfoList){
                //置空token
                sysUserLoginInfoMapper.tokenNull(loginInfo.getId());

                SysUserLoginHistory historyData = sysUserLoginHistoryMapper.selectMaxIdByLoginInfoId(loginInfo.getId());
                if (!ObjectUtils.isEmpty(historyData)){
                    historyData.setLogoutTime(new Date());
                    historyData.setEffectiveTime(historyData.getLogoutTime());
                    sysUserLoginHistoryMapper.updateBatch(historyData);
                }
            }
        }


        return ResponseData.success();
    }

    @Override
    public ResponseData delCompanyArea(DelReq req, Long loginInfoId) {
        SysCompanyArea companyArea = sysCompanyAreaMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(companyArea)){
            return ResponseData.fail("未找到此大区");
        }
        if (companyArea.getIsDeleted() == 1){
            return ResponseData.fail("大区已被删除无法重复删除");
        }
        if(sysAgentInfoMapper.findAgentNumByAreaId(companyArea.getId())>0){
            return ResponseData.fail("该大区下拥有代理商，无法删除");
        }
        int count = sysUserLoginInfoMapper.selectAreaId(req.getId());
        if (count > 0){
            return ResponseData.fail("该大区有帐号关联,无法删除");
        }

        SysCompanyArea area = new SysCompanyArea();
        area.setId(req.getId());
        area.setUpdaterId(loginInfoId);
        area.setUpdatedAt(new Date());
        area.setIsDeleted((byte) 1);
        sysCompanyAreaMapper.updateByPrimaryKeySelective(area);
        return ResponseData.success();
    }

    @Override
    public List<CompanyAreaResp> exList(CompanyAreaReq req) {
        return sysCompanyAreaMapper.page(req);
    }

    @Override
    public ResponseData<List<CompanyManageAreaResp>> searchOpen(Long areaId) {
        return ResponseData.success(sysCompanyAreaMapper.selectList((byte) 1,areaId));
    }

    @Override
    public ResponseData<List<RegionTreeResp>> getRegionTree(RegionTreeReq req) {
        List<Long> storedIds = this.storedIds(req);
        List<RegionTreeResp> allArea = sysCompanyAreaMapper.allArea();
        for (RegionTreeResp region : allArea) {
            List<AgentTreeDTO> allAgent = sysAgentInfoMapper.allAgentByAreaId(region.getAreaId());
            region.setAgentList(allAgent);
            boolean agentCheck = false;
            for (AgentTreeDTO agent : allAgent) {
                List<StoreTreeDTO> allStore = sysStoreInfoMapper.allStoreByStoreId(agent.getAgentId());
                agent.setStoreList(allStore);
                boolean storeCheck = false;
                if (!StringUtils.isEmpty(storedIds)) {
                    for (StoreTreeDTO store : allStore) {
                        if (req.getStoreIds().contains(store.getStoreId())) {
                            store.setChoose((byte) 1);
                            storeCheck = true;
                        }
                    }
                }
                if (storeCheck) {
                    agent.setChoose((byte) 1);
                    agentCheck = true;
                }
            }
            if (agentCheck) {
                region.setChoose((byte) 1);
            }
        }
        return ResponseData.success(allArea);

    }

    @Override
    public List<Long> storedIds(RegionTreeReq req) {
        List<Long> storeIds = new ArrayList<>();
        List<Long> storeIds2 = new ArrayList<>();
        if (req.getAreaIds().size() > 0){
            storeIds = sysStoreInfoMapper.selectInfoIdByAreaIds(req.getAreaIds());
        }
        if (req.getAgentIds().size() > 0){
            storeIds2 = sysStoreInfoMapper.selectInfoIdByAgentIds(req.getAgentIds());
        }
        storeIds.removeAll(storeIds2);
        storeIds.addAll(storeIds2);
        storeIds.removeAll(req.getStoreIds());
        storeIds.addAll(req.getStoreIds());
        return storeIds;
    }

    @Override
    public List<Long> agentIds(RegionTreeReq req) {
        List<Long> agentIds = new ArrayList<>();
        if (req.getAreaIds().size() > 0){
            agentIds = sysStoreInfoMapper.selectAgentIdByAreaIds(req.getAreaIds());
        }
//        areaIds.addAll(areaIds);
        return agentIds;
    }

    @Override
    public List<Long> allAreaId() {
        return sysCompanyAreaMapper.areaById(null);
    }

    @Override
    public SysCompanyArea selectById(Long id) {
        return sysCompanyAreaMapper.selectByPrimaryKey(id);
    }


}
